package com.birdboot.core;

import com.birdboot.http.HttpServletRequest;
import com.birdboot.http.HttpServletResponse;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;

//该类是SpringMVC框架与Tomcat集合的一个关键类
//Tomcat
//
//
public class DispatcherServlet {
    private static File baseDir;//类加载路径
    private static File staticDir;//类加载路径下的static目录
    static { //定位当前项目的类加载路径
        try {
            baseDir = new File(
                    DispatcherServlet.class.getClassLoader().getResource(".").toURI()
           );
            //定位类加载路径下的static目录
            staticDir = new File(baseDir, "static");
        } catch (URISyntaxException uriSyntaxException) {
            uriSyntaxException.printStackTrace();
        }
    }

    /*
    * service方法实际上是*/
    public void service(HttpServletRequest request,HttpServletResponse response) throws IOException {


        //获取请求的抽象路径
        String path = request.getUri();
        System.out.println(path);

        File file = new File(staticDir, path);

            /*
                V7改造
                1:将原来在这里定义的两个局部变量statusCode和statusReason删除
                2:将处理结果设置到response对应的属性上
                3:将发送响应的操作移动到HttpServletResponse的response方法中
                  并在第三步发送响应时改为调用response方法发送响应
             */
        if (file.isFile()) {
            //由于响应对象中状态代码和描述默认值为200，OK因此正确情况下不用再设置
            response.setContentFile(file);
        } else {
            response.setStatusCode(404);
            response.setStatusReason("NotFound");
            file = new File(staticDir, "404.html");
            response.setContentFile(file);
        }

        //3 发送响应
        response.response();

    }
}
